<template>
  <!-- 添加共享的 弹窗   -->
  <el-dialog title="添加共享" :visible.sync="dialogVisible" @close="close" :close-on-click-modal="false" width="1000px">
    <div class="new_form_box" v-loading="loading">
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="90px" class="demo-ruleForm">
        <el-form-item label="" label-width="0" prop="carrierId">
          <div class="select-box">
            <selectBtnVue :options="{
              valueKey: 'id',
              labelKey: 'name',
              itemWidth: '100px',
              itemHeight: '38px',
              limitShow: '100',
            }" :selected="form.carrierId" :list-data="carrierTypes" @change="selectYYSType"></selectBtnVue>
          </div>
        </el-form-item>
        <div class="tip" v-if="noSet">
          当前运营商未找到共享设置，点击<span class="link" @click="openSet">立即设置</span>
        </div>
        <div class="tip" v-if="!telNumberListInit||telNumberListInit.length==0">
          当前运营商没有可用号码！
        </div>
        <el-form-item label="分配方式" prop="fenpeiType">
          <el-radio-group :disabled="isDisabled" v-model="form.fenpeiType" @change="fenpeifangshiChange">
            <el-radio :label="1">共享市场</el-radio>
            <el-radio :label="2">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用方" prop="zulinfangId" v-if="form.fenpeiType==2">
          <el-select :disabled="isDisabled" @change="selectChange" v-if="tenantList&&tenantList.length" v-model="form.zulinfangId" placeholder="请选择店铺" clearable filterable>
            <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
          </el-select>
        </el-form-item><br />
        <el-form-item label="选择号码" prop="xuanhaoType">
          <el-radio-group :disabled="isDisabled" v-model="form.xuanhaoType" @change="xuanhaoTypeChange">
            <el-radio :label="1">随机分配</el-radio>
            <el-radio :label="2">指定号码</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="号码数量" prop="num" v-if="form.xuanhaoType==1">
          <el-input :disabled="isDisabled" @change="jisuan" style="width:100px" :controls="false" v-model="form.num" placeholder="请输入"></el-input>

          <span style="padding-right: 10px;color: #999;">可分配数: <span>{{telNumberListInit.length||'--'}}</span></span>
        </el-form-item>
        <el-form-item label="选择号码" prop="num" v-if="form.xuanhaoType==2">
          <span>
            <el-button :disabled="isDisabled" plain @click="openPhoneSelect">点击选择</el-button>
            <span style="padding-right: 10px;color: #999;margin-left: 10px;">已选号码: <span>{{form.num||0}}</span></span>
            <span style="padding-right: 10px;color: #999;">可分配数: <span>{{telNumberListInit.length||'--'}}</span></span>
          </span>
        </el-form-item>
        <br />
        <el-form-item label="单价" prop="" v-if="form.fenpeiType==2">
          <div style="width: 190px;">
            {{ shareSetObj[form.carrierId].monthPrice }}元/卡/月
          </div>
        </el-form-item>
        <el-form-item label="使用时长" prop="monthNum" v-if="form.fenpeiType==2">
          <el-input :disabled="isDisabled" @change="jisuan" style="width:100px" :controls="false" v-model="form.monthNum" placeholder="请输入"></el-input>
          <span style="display: inline-block;width: 100px;">月</span>
        </el-form-item>
      </el-form>
    </div>
    <div class="price-box flex alc" v-if="form.fenpeiType==2">
      <template>
        <div class="flex alc">
          使用费：
          <span class="price1"> ¥{{ form.shiyongfei||0 }}</span>
        </div>
        <div class="flex alc">
          服务费：
          <span class="price1"> ¥{{ form.fuwufei||0 }}</span>
        </div>
        <div class="flex alc">
          应付金额：
          <span class="red">¥ </span> <span class="price"> {{ form.shifu||0 }}</span>
        </div>
      </template>
    </div>
    <div class="price-box yue flex alc" v-if="form.fenpeiType==2">
      <template>
        <div class="flex alc">
          当前余额：
          <span class="price1"> ¥{{ shopInfo.availableMoney||0 }}</span>
        </div>
      </template>
    </div>

    <div class="tip">提示：服务费{{fuwufeidanjia}}元/卡/月</div>
    <div v-if="form.fenpeiType==2" class="tip">
      您直接指定用户进行分享卡位，卡位使用费请自行收取！卡位共享服务费将由您承担。
    </div>

    <div slot="footer" class="center">
      <el-button @click="close()">取消</el-button>
      <el-button :disabled="isDisabled" type="primary" @click="submitForm" :loading="loading">
        <span v-if="form.fenpeiType==2">支付</span>
        <span v-if="form.fenpeiType==1">提交</span>
      </el-button>
    </div>

    <div class="haoma">
      <el-dialog title="选择号码" :visible.sync="telNumberShow" @close="close2" append-to-body :close-on-click-modal="false" width="860px">
        <div>
          <!-- <div>
            请选择要分配的号码：
          </div> -->
          <div class="flex">
            <el-input style="width: 200px;margin-right: 15px;" v-model="queryParams.tel" placeholder="请输入手机号" clearable size="small" />
            <el-button type="primary" @click="search">搜索</el-button>

            <el-input type="textarea" style="width:400px;margin-right: 15px;margin-left: 15px;" v-model="queryParams.telText" placeholder="请输入批量手机号, 多个手机号用空格或换行隔开" clearable />
            <el-button type="primary" @click="piliang">批量搜索</el-button>
            
          </div>
          <div style="color:red;margin-top: 10px;" v-if="notTel&&notTel.length">
           未找到的手机号：
            {{ notTel.join(',') }}
          </div>
          <div style="min-height: 300px;" v-if="telNumberList&&telNumberList.length">
            <div style="margin: 7px 0;">
              <myCheckbox @change="isAllCheckChange" v-model="isAllCheck" :list="[{id:2,name:'全选'}]"></myCheckbox>
            </div>
            <div class="">
              <myCheckbox v-model="checkTelNumberList" :list="telNumberList" :option="{valueKey: 'id',labelKey: 'tel',heduiState:true}">
              </myCheckbox>
            </div>
          </div>
          <div style="min-height: 300px;" v-else>
            <el-empty description="暂无手机号"></el-empty>
          </div>
        </div>
        <div slot="footer" class="center">
          <el-button @click="close2()">取消</el-button>
          <el-button type="primary" @click="saveTelNumber" :loading="loading">提交</el-button>
        </div>
      </el-dialog>
    </div>
    <shareSet ref="shareSet" @saved="setSaved"></shareSet>
  </el-dialog>
</template>
<script>
import phoneApi from "@/api/phoneManage";
import selectBtnVue from "../../../components/select-btn.vue";
import {
  addtenantPushSettings,
  getTenantPushSettingsByTenantId,
  delTenantPushSettings,
} from "@/api/system/shopManage";
import shareSet from "./shareSet.vue";
export default {
  name: "",
  components: { selectBtnVue, shareSet },
  data() {
    return {
      isAllCheck: [],
      telNumberListInit: [], //初始 可选的号码列表
      telNumberList: [], //可选的号码列表
      checkTelNumberList: [], //选择的号码列表
      telNumberShow: false,
      dialogVisible: false,
      loading: false,
      // totalPhoneNumber: 0,
      form: {
        carrierId: 1,
        fenpeiType: 1,
        zulinType: 1,
        zulinfangId: "",
        xuanhaoType: 1,
        num: "",
        monthNum: "",
        telInfo: [],
        shiyongfei: "",
        fuwufei: "",
        shifu: "",

        orderSource: 2, //1共享市场 2指定用户
        carrierName: "腾讯",
        chuzufangId: "",
        chuzufangName: "",
        zulinfangName: "",
      },
      selectTenantInfo: "",
      queryParams: {
        pageSize: 10,
        pageNum: 1,
        telText:'',
        tel:''
      },
      rules: {
        fenpeiType: [{ required: true, message: "请选择", trigger: "change" }],
        xuanhaoType: [{ required: true, message: "请选择", trigger: "change" }],
        num: [{ required: true, message: "请输入", trigger: "change" }],
        monthNum: [
          { required: true, message: "请输入", trigger: "change" },
          { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" },
          { max: 120, message: "不能超过120", trigger: "blur" },
        ],
      },

      currentRow: null,
      shareSetObj: {},
      isDisabled: false,
      noSet: false,
      shifu: "",
      fuwufeidanjia:1,
      notTel:[]
    };
  },
  created() {},
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
    carrierTypes() {
      return this.$store.getters.gameYunyingshangList;
    },
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
  },
  methods: {
    // 打开弹窗
    async open() {
      this.dialogVisible = true;

      this.form.chuzufangId = this.shopInfo.tenantId;
      this.form.chuzufangName = this.shopInfo.tenantName;
      this.form.xuanhaoType = 1
      this.form.shiyongfei = ''
      this.form.fuwufei = ''
      this.form.shifu = ''

      await this.getShareSet();
      
      this.selectYYSType(1);
      this.getFuwufeidanjia()
    },
    /** 查询共享设置 */
    async getShareSet() {
      this.shareSetObj = {};
      const res = await getTenantPushSettingsByTenantId({
        tenantId: this.shopInfo.tenantId,
        type: 9,
      });
      if (res.data && res.data.settingsJson) {
        const resobj = JSON.parse(res.data.settingsJson);
        this.shareSetObj = resobj;
      }
    },
    // 查询卡位服务费单价
    async getFuwufeidanjia(){
      const res = await this.getDicts("kaweifuwufei");
      if (res.data && res.data.length) {
        const obj = this.arrayToObject(res.data, "dictLabel");
        if(obj.kaweifuwufei&&obj.kaweifuwufei.dictValue){
          this.fuwufeidanjia = Number(obj.kaweifuwufei.dictValue)
        }
      }
    },
    // 运营商改变
    selectYYSType(e) {
      this.isDisabled = false;
      this.noSet = false;
      this.form.carrierId = e;
      if(this.carrierTypes&&this.carrierTypes.length){
        this.carrierTypes.forEach(r=>{
          if(r.id==e){
            this.form.carrierName = r.name;
          }
        })
      }
      // 清空已填写的数据
      this.form.num = "";
      this.form.zulinfangId = "";
      this.checkTelNumberList = [];
      // 初始化可选的号码
      this.initTelList();
      if (
        this.shareSetObj[e] &&
        this.shareSetObj[e].monthPrice &&
        this.shareSetObj[e].fuwufeiType
      ) {
      } else {
        // 当前运营商没有 共享设置  提醒用户进行设置
        this.isDisabled = true;
        this.noSet = true;
      }
    },
    // 打开共享设置
    openSet() {
      this.$refs.shareSet.open();
    },
    // 保存了共享设置
    async setSaved() {
      await this.getShareSet();
      this.selectYYSType(this.form.carrierId);
    },
    // 时长和数量改变
    jisuan() {
      if (this.form.num && this.form.monthNum) {
        const zujin =
          this.form.num *
          this.form.monthNum *
          this.shareSetObj[this.form.carrierId].monthPrice;
        this.form.shiyongfei = zujin;
        this.form.fuwufei = this.form.num * this.form.monthNum*this.fuwufeidanjia
        this.form.shifu = this.form.fuwufei;
      }
      // // 计算到期时间
      // if (this.form.monthNum && Number(this.form.monthNum)) {
      //   const result = new Date();
      //   result.setMonth(result.getMonth() + Number(this.form.monthNum));
      //   const r = this.parseTime(result, "{y}-{m}-{d}");
      //   this.form.expireTime = r;
      // }
    },

    // 打开选择号码的弹窗
    openPhoneSelect() {
      this.checkTelNumberList = [];
      this.isAllCheck = [];
      this.telNumberShow = true;
      this.notTel = []
      this.queryParams.telText = ''
      this.queryParams.tel = ''
      this.search()
      // 回显已经选择的号码
      if (this.form.telInfo && this.form.telInfo.length) {
        this.form.telInfo.forEach((r) => {
          this.checkTelNumberList.push(r.id);
        });
      }
    },
    // 查询可选的手机号码
    async initTelList() {
      this.telNumberList = [];
      
      let res
      try {
        res = await phoneApi.getWeiGongXiang({
          carrierId: this.form.carrierId,
        });
      } catch (error) {
        
      }
      if (res.data && res.data.unLeaseInfo && res.data.unLeaseInfo.length) {
        res.data.unLeaseInfo.forEach((r) => {
          this.telNumberList.push({
            id: r.split("-")[0],
            tel: r.split("-")[1],
            heduiState: r.split("-")[2]||1,
          });
        });
      } else {
        this.isDisabled = true;
      }
      this.telNumberListInit = JSON.parse(JSON.stringify(this.telNumberList));
    },
    // 测试
    piliang(){
      if(this.queryParams.telText){
        const replacedString = this.queryParams.telText.replace(/\s+/g, ',')
        console.log("%c Line:357 🍺 replacedString", "color:#b03734", replacedString);
        const arr = replacedString? replacedString.split(',') :[]
        this.notTel = []
        if(arr&&arr.length){
          // 匹配选中的手机号
          this.telNumberList = this.telNumberListInit.filter((r) =>
            arr.includes(r.tel)
          );
          // 找出未找到的手机号
          if(this.telNumberList&&this.telNumberList.length){
              arr.forEach(r3=>{
                let flag = true
                this.telNumberList.forEach(r2=>{
                  if(r3==r2.tel){
                    flag = false
                  }
                })
                if(flag){
                  this.notTel.push(r3)
                }
              })
          }else{
            this.notTel = JSON.parse(JSON.stringify(arr))
          }
        }else{
          return this.$message.error('请输入批量手机号, 多个手机号用空格或换行隔开')
        }
      }else{
        this.telNumberList = JSON.parse(JSON.stringify(this.telNumberListInit));
      }
      
    },
    // 查找号码
    search() {
      if (this.queryParams.tel) {
        this.telNumberList = this.telNumberListInit.filter((r) =>
          r.tel.includes(this.queryParams.tel)
        );
      } else {
        this.telNumberList = JSON.parse(JSON.stringify(this.telNumberListInit));
      }
    },
    // 全选号码
    isAllCheckChange(e) {
      this.checkTelNumberList = [];
      if (this.isAllCheck && this.isAllCheck.length) {
        this.telNumberList.forEach((r) => {
          this.checkTelNumberList.push(r.id);
        });
      }
    },
    // 选择号码完成
    saveTelNumber() {
      if (this.checkTelNumberList.length == 0) {
        return this.$message.error("请选择号码！");
      }
      const temp = [];
      this.checkTelNumberList.forEach((id) => {
        this.telNumberListInit.forEach((r) => {
          if (r.id == id) {
            temp.push(r);
          }
        });
      });
      this.form.num = this.checkTelNumberList.length;
      this.form.telInfo = JSON.parse(JSON.stringify(temp));
      this.close2();
      this.jisuan();
    },
    // 获取可用的手机号
    getList() {},
    // 分配方式改变
    fenpeifangshiChange(e) {
      this.form.zulinfangId = "";
      this.form.monthNum = "";
      // this.getList();
    },
    // 选号类型改变
    xuanhaoTypeChange() {
      this.form.num = "";
      this.form.telInfo = null;
      this.checkTelNumberList = [];
    },
    // 选择店铺改变
    selectChange(e) {
      this.tenantList.forEach((r) => {
        if (r.tenantId == e) {
          this.form.zulinfangName = r.tenantName;
          // this.selectTenantInfo = { ...r };
        }
      });
    },

    // 重置
    reset() {
      this.form = {
        pageNum: 1,
        pageSize: 10,
      };
      this.$refs.form.resetFields();
    },

    submitForm(formName) {
      // 表单校验
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.num > this.telNumberListInit.length) {
            return this.$message.error("号码数量不能超过可分配数量！");
          }
          if (this.form.fenpeiType == 2) {
            // 指定用户  直接出租
            // 二次确认，提示将从余额支付
            this.$confirm(
              `卡位使用费请自行收取！服务费${this.form.shifu}元将使用您的余额支付，确认支付吗？`,
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                this.loading = true;
                phoneApi
                  .telShareOrderPay(this.form)
                  .then((res) => {
                    this.loading = false;
                    this.$message.success(res.msg);
                    this.dialogVisible = false;
                    this.$parent.getList();
                    this.$store.dispatch("getShopInfo");
                  })
                  .catch((err) => {
                    this.loading = false;
                  });
              })
              .catch(() => {});
          } else {
            // 加入共享市场
            this.loading = true;
            const obj = {
              ...this.form,
            };
            obj.telLeaseDetailsVos = [
              {
                carrierId: obj.carrierId,
                telInfo: obj.telInfo,
                num: obj.num,
                // expireTime: obj.expireTime,
              },
            ];
            // return;
            phoneApi
              .telLeaseDetailsSaveGX(obj)
              .then((res) => {
                this.loading = false;
                this.$message.success(res.msg);
                this.dialogVisible = false;
                this.$parent.getList();
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
        }
      });
    },
    close() {
      this.resetForm("form");
      this.dialogVisible = false;
    },

    close2() {
      this.telNumberShow = false;
    },
  },
};
</script>
<style scoped lang="scss">
.tip {
  color: #999;
  margin-bottom: 8px;
}
::v-deep .el-radio input[aria-hidden="true"] {
  display: none !important;
}
.price-box {
  color: #999;
  padding: 10px;
  border-radius: 8px;
  background-color: #f8f8f8;
  min-height: 50px;
  &.yue {
    height: 36px;
    margin: 10px 0;
  }
  // margin-top: 10px;
  > div {
    margin-right: 15px;
  }
  .price1 {
    color: #666;
    line-height: 26px;
    // font-size: 18px;
  }
  .price {
    font-size: 26px;
    color: red;
  }
}
.red {
  color: red;
}
</style>
